﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleScale.DataAccess;
using VehicleScale.Models;

namespace VehicleScale.Forms.Files
{
    public partial class FrmUpdateProducts : TemplateForm
    {
        #region Ctors
        public FrmUpdateProducts()
        {
            InitializeComponent();

            Initialize();

            this.BackColor = Setting.BackColor;
            this.uiGroupBox1.BackColor = Setting.BackColor;
            this.Size = new Size(400, 300);

        }
        #endregion

        #region Singleton Members
        //private static volatile FrmUpdateProducts instance;
        //private static object syncRoot = new Object();

        ///// <summary>
        ///// Create Instance
        ///// </summary>
        //public static FrmUpdateProducts Instance
        //{
        //    get
        //    {
        //        lock (syncRoot)
        //        {
        //            if (instance == null)
        //                instance = new FrmUpdateProducts();
        //        }

        //        return instance;
        //    }
        //}

        ///// <summary>
        ///// Free Instance
        ///// </summary>
        ///// <param name="e"></param>
        //protected override void OnClosed(EventArgs e)
        //{
        //    //instance = null;
        //    base.OnClosed(e);
        //}

        #endregion

        #region Field Members
        private bool _isEdit = false;
        private bool _isBinding = false;
        private IProductDataAccess _dataAccess = new ProductDataAccess();
        #endregion

        #region Property Members
        private ProductModel _product = new ProductModel();
        public ProductModel Product
        {
            get { return _product; }
            set
            {
                if (_product != value)
                {
                    _isEdit = true;
                    _product = value;
                }
            }
        }

        public IList<CategoryModel> Categories
        {
            set
            {
                this.cboCategoryID.DataSource = value;
                this.cboCategoryID.ValueMember = "CategoryID";
                this.cboCategoryID.DisplayMember = "CategoryName";
            }
        }

        private IList<ProductModel> _collection;
        public IList<ProductModel> Collection
        {
            set { _collection = value; }
        }
        #endregion

        #region Methods

        private void Initialize()
        {
            this.MaximizeBox = false;

            this.Load += new EventHandler(delegate
            {
                BindingControls();
                ValidatingControls();
            });
            this.btnSave.Click += new EventHandler(delegate { ClickButtonSave(); });
            this.btnClose.Click += new EventHandler(delegate { this.Close(); });
        }

        protected override void OnLoad(EventArgs e)
        {
            if (_isEdit)
                this.edtProductID.Enabled = false;
            base.OnLoad(e);
        }

        private void ResetBindingControls()
        {
            this.edtProductID.DataBindings.Clear();
            this.edtProductName.DataBindings.Clear();
            this.edtUnit.DataBindings.Clear();
            this.cboCategoryID.DataBindings.Clear();
            this._isBinding = false;
        }
        private void BindingControls()
        {
            if (!_isBinding)
            {
                this.edtProductID.DataBindings.Add("Text", Product, "ProductID");
                this.edtProductName.DataBindings.Add("Text", Product, "ProductName");
                this.edtUnit.DataBindings.Add("Text", Product, "Unit");
                this.cboCategoryID.DataBindings.Add("Value", Product, "CategoryID");
                _isBinding = true;
            }
        }
        private void ValidatingControls()
        {
            string errorMessage = String.Empty;
            this.edtProductName.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtProductName.Text) ?
                    ErrorException.Error("Tên sản phẩm", errType.required) : String.Empty;
                errorProvider.SetError(this.edtProductName, errorMessage);
            });

            this.edtUnit.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtUnit.Text) ?
                    ErrorException.Error("Đơn vị tính", errType.required) : String.Empty;
                errorProvider.SetError(this.edtUnit, errorMessage);
            });

        }
        #endregion

        #region Action Members

        /// <summary>
        /// Click button save
        /// </summary>
        private void ClickButtonSave()
        {
            bool invalidInput = false;

            foreach (Control ctrl in this.Controls)
            {
                if (errorProvider.GetError(ctrl) != String.Empty)
                {
                    invalidInput = true;
                    break;
                }
            }

            if (invalidInput)
            {
                Library.Tools.MsgBox.Show(Messages.ValidateInfoMessage, Messages.NoticeTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                this.errorProvider.Clear();

                bool result = false;
                if (!_isEdit)
                {
                    result = _dataAccess.Add(_product);

                    if (result)
                    {
                        Common.Products.Add(_product);
                        _collection.Add(_product);
                        _product = new ProductModel();
                        ResetBindingControls();
                        BindingControls();
                        try
                        {
                            LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Them moi san pham : " + _product.ProductName);
                        }
                        catch
                        {
                        }
                            this.edtProductID.Focus();
                    }
                    else
                    {
                        Library.Tools.MsgBox.Show(String.Format(Messages.NewFailedMessage, "sản phẩm"),
                            "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    result = _dataAccess.Edit(_product);

                    if (result)
                    {
                        var query = (from c in Common.Products
                                     where c.ProductID == _product.ProductID
                                     select c).SingleOrDefault();
                        if (query != null)
                        {
                            _product.CopyTo<ProductModel>(query);
                        }
                        try
                        {
                            LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Thay doi san pham : " + _product.ProductName);
                        }
                        catch
                        {
                        }
                            this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        Library.Tools.MsgBox.Show(String.Format(Messages.ModifyFailedMessage, "sản phẩm"),
                            "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                }
            }
        }

        #endregion
    }
}
